package com.flitsneak.rabbit.consumer;

import com.flitsneak.common.entity.Info;
import com.flitsneak.common.entity.Messages;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/8/10 14:39
 * @description
 */
@RabbitListener(queues = {"hello-queue"})
@Slf4j
@Component
public class RabbitConsumer {
    /**
     * org.springframework.amqp.core,Message 原生消息的详细信息 头+体
     *
     */
//    @RabbitListener(queues = {"hello-queue"})
//    public void receiveMessage(Message message){
//        //消息体
//        byte[] body = message.getBody();
//        //消息头
//        MessageProperties messageProperties = message.getMessageProperties();
//
//        log.info("收到消息：{}",message);
//    }

    // Queue: 可以很多人都来监听，只要收到消息，队列删除消息，而且只能有一个收到此消息。
    // 同一个消息只能有一个客户端收到，多个服务是竞争关系
    // 默认是只有当前消息处理完才会处理下一个消息
    // @RabbitListener(queues = {"hello-queue"})
    // Message JavaMessage Channel
    @RabbitHandler
    public void receiveMessageEntity(Message message, Messages messages, Channel channel){
        //消息体
        //byte[] body = message.getBody();
        //消息头
        //MessageProperties messageProperties = message.getMessageProperties();

        log.info("收到消息：{}",messages);
        //顺序自增
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            //手动ack deliveryTag,multiple 签收 非批量模式
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    @RabbitHandler
    public void receiveInfoEntity(Message message, Info info, Channel channel){
        log.info("收到消息：{}",info);

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            //deliveryTag,multiple,requeue 三个参数 重新入队会被重新发送签收
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            //deliveryTag requeue
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("rabbit接收信息出错！");
        }
    }
}
